package com.refusea.remoting.baidu

import com.alibaba.fastjson2.JSON
import com.refusea.commons.http.Https
import com.refusea.commons.http.Https.Companion.success
import com.refusea.remoting.baidu.io.BaiduCensorResult
import com.refusea.remoting.baidu.io.BaiduToken
import com.refusea.train.domain.ex.BizEx
import org.slf4j.Logger
import org.slf4j.LoggerFactory

/**
 * @author Zhang Yan 2024/4/27
 **/
object BaiduApi {

    private val log: Logger = LoggerFactory.getLogger(BaiduApi::class.java)

    // https://ai.baidu.com/ai-doc/REFERENCE/Ck3dwjhhu
    private fun refreshToken() {
        if (token.valid()) {
            return
        }

        val rsp = http.get(TOKEN_URL)
        if (rsp.success) {
            token = JSON.parseObject(rsp.body(), BaiduToken::class.java)
        } else {
            throw BizEx.of("获取百度访问令牌失败")
        }
    }

    // https://ai.baidu.com/ai-doc/ANTIPORN/Rk3h6xb3i
    fun textCensor(text: String): Boolean {
        refreshToken()
        val rsp = http.post("${TEXT_CENSOR_URL}${token.accessToken}", headers, emptyList(), "text=$text")
        if (rsp.success) {
            val result = JSON.parseObject(rsp.body(), BaiduCensorResult::class.java)
            if (result.legal()) {
                return true
            }
            log.warn("百度文本内容审核结果：${rsp.body()}")
            return false
        } else {
            throw BizEx.of("百度文本内容审核失败")
        }
    }

    // https://ai.baidu.com/ai-doc/ANTIPORN/jk42xep4e
    fun imageCensor(url: String): Boolean {
        refreshToken()
        val rsp = http.post("${IMAGE_CENSOR_URL}${token.accessToken}", headers, emptyList(), "imgUrl=$url")
        if (rsp.success) {
            val result = JSON.parseObject(rsp.body(), BaiduCensorResult::class.java)
            if (result.legal()) {
                return true
            }
            log.warn("百度图片内容审核结果：${rsp.body()}")
            return false
        } else {
            throw BizEx.of("百度图片内容审核失败")
        }
    }


    private var token = BaiduToken("", 0L)

    private const val APP_ID = "?"
    private const val API_KEY = "?"
    private const val SECRET_KEY = "?"

    private const val TOKEN_URL =
        "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${API_KEY}&client_secret=${SECRET_KEY}"

    private const val TEXT_CENSOR_URL =
        "https://aip.baidubce.com/rest/2.0/solution/v1/text_censor/v2/user_defined?access_token="

    private const val IMAGE_CENSOR_URL =
        "https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token="

    private val http = Https()

    private val headers = listOf("Content-Type" to "application/x-www-form-urlencoded")
}
